--data
require "data.uid"
require "data.nodes"
require "data.prototypes"

--simulation
function interface (node)
  return function (...)
    node.handle(...)
  end
end

ghost = {
}

simulatednodes ={
  add = function(self,node)
    self[node.uid]=interface(node)
  end,
  remove = function(self,node)
    local uid = 0
    if (type(node) == node) then
      uid = node.uid
    else
      uid = node--we passed an id not a node
    end
    --should probably save here
    self[uid] = nil  
  end, 
  __ghost = interface(ghost),
}

simulatednodes_mt = {
  __index = function(t,k)
    --we are accessing an unheld node
    --forward to ghost
    return t.__ghost
  end
}


--Decode data sent as lua or json
function decode(s)
  local t = none
  if (string.sub(s, 1, 4) == "json") then --json object   
     t = json.decode(s,5)--don't parse the word "json"
  else
     t = unmarshall(s)
  end
  return t
end  

--Handle incomming data
function handler(data,session) -->all incomming data will pass through this filter
    if (data == "shutdown") then
      return false, "shutdown"
    else
      local reply = "ok"
      local d = decode(data)
      local cmd = ""
      if type(d)=="table" then
        print('data:')
        print(marshall('data',d))--print the table i got
        cmd = d["cmd"] 
      else
        print('data:',d)
        cmd = d
      end
      local ok
      ok, reply = pcall(events[cmd],d)
      if ok then
        --hanlded rpc
        printf("handled event: [%s:%s]",cmd,reply)
      else
        --unhandled rpc
        printf("unhandled event: [%s:%s]",cmd,reply)
      end  
      return true, reply
    end
end

--remote event table
events = {}
events.onlogin = function(data)
  local uid = uid[data.user]
  if (uid) then
    simulatednodes[uid] = nodes[uid]
    return uid
  else
    return 0
  end
  
end
timers = {}

function update(dt)

end

--Main entrypoint
function main(args)
  local args = args or {}
  myservice = {
    name      = "server",
    hndserver = none, -->The service will assign a handler here
    ip        = args.host or "localhost",
    port      = args.port or 222,
    frequency = 1, -->seconds
    breakpattern = nil,
    filter    = handler
  } 
  service.service(myservice)
  return 1
end
